<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * Website-based book, bound in Textile :)
 *
 * @package    Fabryc
 * @author     J.B. Early
 * @copyright  (c) 2009 J.B. Early
 */
class Fabryc_Core {

	protected $config;
	protected $prefix;		// url prefix
	protected $suffix;		// fabryc file suffix
	protected $index;		// index file name
	protected $root;		// fabryc document root
	protected $root_index;	// root index file

	public function __construct($config = array())
	{
		$this->config	= $config + Kohana::config('fabryc');

		$this->prefix	= $this->config['prefix'];
		$this->suffix	= $this->config['suffix'];
		$this->index	= $this->config['index'].$this->suffix;
		$this->root		= DOCROOT.$this->config['root'];
	}

	public function get_filepath($args)
	{
		$path = $this->root;
		while( $ref = array_shift($args)) {
			if (is_dir($path.$ref)) {
				$path .= "$ref/";
			} elseif (file_exists($p = $path.$ref.$this->suffix)) {
				return $p;
			} else {
				return null;
			}
		}

		$path .= $this->index;
		return file_exists($path) ? $path : null;
	}

	public function get_menu($args)
	{
		return $this->get_menu_from_file($this->prefix,$this->root,$this->index,$args);
	}

	private function get_menu_from_file($prefix,$root,$fc,$args,$pad='')
	{
		$p = new Processor;
		$p->load_file($root.$fc);

		$toks = array('##','menu');
		$arg  = array_shift($args);
		$menu = array();

		foreach ($p->lines() as $line) {
			if (2==util::matchTok($toks,$line)) {
				if ( ! ($ref = util::getTok($line))) {
					// empty menu directive, silently ignore
					continue;
				}

				if ( ! ($tag = util::getTok($line))) $tag = $ref;

				$m = array($pad.$tag=>$prefix.$ref);
				if ($arg==$ref) {
					$mm = array();
					if (is_dir($root.$ref)) {
						$mm = $this->get_menu_from_file("$prefix$ref/","$root$ref/",$this->index,$args,'&nbsp;'.$pad);
					} elseif (file_exists($root.($fc=$ref.$this->suffix))) {
						$mm = $this->get_menu_from_file($prefix,$root,$fc,array(),'&nbsp;'.$pad);
					}
					foreach ($mm as $mi) {
						foreach ($mi as $tag=>$ref) {
							$m[$tag] = $ref;
						}
					}
				}
				$menu[] = $m;
			}
		}

		return $menu;
	}

	private function process(Processor $p)
	{
		require_once dirname(__FILE__).'/classTextile.php';
		$t = new Textile();

		$p->process();
		$text = $t->TextileThis($p->text);
		$text = $p->typography($text);
		$text = $p->unescapeText($text);

		return array($text,$p->keywords,$p->description,$p->errors);
	}

	public function process_file($path)
	{
		return $this->process(Processor::from_file($path));
	}

	public function process_text($text)
	{
		return $this->process(Processor::from_text($text));
	}
}

// eof